package com.bop.dehong.center;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import com.base.dehong.util.DeviceUuidFactory;
import com.base.dehong.util.DateUtil;
import com.base.dehong.util.LogUtils;
import com.base.dehong.util.StringUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.base.TopManager;
import com.bop.dehong.center.transaction.TransactionActivity;
import com.bop.dehong.config.Config;
import com.bop.dehong.util.CodeUtil;
import com.bop.dehong.util.WebUrlUtil;
import com.bop.dehong.webview.WebViewActivity;

/**
 * 提现
 * @author TangWenhan/YeFengyun
 *2015-11-18上午10:05:16
 */
public class WithdrawalsActivity extends BaseActivity implements TextWatcher, android.widget.CompoundButton.OnCheckedChangeListener{
	private TextView mCanWithdrawalsTv;//可提现金额
	private EditText mMoneyTv,mCodeEt;//提现
	private RadioGroup mModeOfWithdrawalsRg;//
	private TextView mCounterFeeTv,mServiceChargeTv;//手续费，服务费
	private TextView mActualMoney;//实际金额
	private ImageButton mCodeIb;
	private final String mNewMode = "IMMEDIATE";
	private final String mQuickMode = "FAST";
	private final String mCommonMode = "GENERAL";
	private String mModel = mNewMode;
	private	String mMoneyStr = "";
	
	private Double mCanMoney = 0.0;
	private boolean mMoneyChanged = true;
	private CheckBox checkBox;
	private boolean isCheck = true;
	private CodeUtil util;
	private String getCode;
	
	@Override
	protected void initTop() {
		View mView = getView(R.id.top);
		TopManager manager = new TopManager(mView);
		manager.setTitle(R.string.shenqingtixian);
		manager.setLeftImageVisibility(View.VISIBLE);
		manager.setRightText("提现记录");
		manager.setRightTextVisibility(View.VISIBLE);
		manager.setRightTextOnClick(this);
	}

	@Override
	protected void initUI() {
		mCanWithdrawalsTv = getView(R.id.textView4);
		mMoneyTv = getView(R.id.textView7);
		mModeOfWithdrawalsRg = getView(R.id.radioGroup1);
		mCounterFeeTv = getView(R.id.textView12);
		mServiceChargeTv = getView(R.id.serviceCharge);
		mActualMoney = getView(R.id.textView15);
		mCodeIb = getView(R.id.codeIb);
		mCodeEt = getView(R.id.code);
		checkBox = getView(R.id.tixian_ckb_xieyi);
		checkBox.setOnCheckedChangeListener(this);
		
		mMoneyTv.addTextChangedListener(this);
		mModeOfWithdrawalsRg.setOnCheckedChangeListener(changeListener);
		mMoneyTv.setOnFocusChangeListener(mMoneyTvListener);
		
		registerOnClickListener(mCodeIb,
				getView(R.id.checkBox1),
				getView(R.id.checkBox2),
				getView(R.id.linearLayout),
				getView(R.id.submit_button)
				);
	}
	

	@Override
	protected void initData() {
		mCanMoney = getIntent().getDoubleExtra("money", 0.0);
		mCanWithdrawalsTv.setText("￥" + StringUtils.getFormatValue(mCanMoney + ""));
		mMoneyTv.setHint("本次最多可提现" + StringUtils.getFormatValue(mCanMoney + "") + "元");
		util = CodeUtil.getInstance();
		mCodeIb.setImageBitmap(util.getBitmap());
		getCode = util.getCode(); //获取显示的验证码
	}
	
	OnCheckedChangeListener changeListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (checkedId <= 0 || !((RadioButton)getView(checkedId)).isChecked()) {
				return;
			}
			if (checkedId == R.id.radioButton1) {
				mModel = mNewMode;
			}else if (checkedId == R.id.radioButton2) {
				mModel = mQuickMode;
			}else if (checkedId == R.id.radioButton3) {
				mModel = mCommonMode;
			}
			calculateCost(mMoneyStr, mModel);
			
		}
	};
	
	@Override
	public void onTitleLeftClick(View v) {
//		setResult(RESULT_OK);
		super.onTitleLeftClick(v);
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                 && event.getRepeatCount() == 0) {
//            setResult(RESULT_OK);
            finishCurrentActivity();
        	return true;
         }
         return super.onKeyDown(keyCode, event);
     }
	
	/**
	 * 计算费用
	 */
	@SuppressLint("SimpleDateFormat")
	private void calculateCost(String money,String mode){
		Double counterFee = 0.0, serviceFee = 0.0;
		if (TextUtils.isEmpty(money)) {
			return;
		}

		if (TextUtils.isEmpty(money)) {
			return;
		}
		Double moneyLong = Double.valueOf(money);
		if (moneyLong > mCanMoney) {
			ToastUtils.show(this, "金额不能大于可提现金额！");
			return;
		}
		if (moneyLong < 0.01) {
			ToastUtils.show(this, "金额必须大于0.01！");
			return;
		}
		serviceFee = moneyLong * 0.003;
		counterFee = 2.0;
		Date date = new Date();
		int dayOfWeek = DateUtil.getDayOfWeek(date);
		if (TextUtils.equals(mode, mNewMode)) {

			if (dayOfWeek == 6) {//周五
				counterFee = moneyLong * 0.0005 * 3 + 2;
			}else if (dayOfWeek == 7){//周六
				counterFee = moneyLong * 0.0005 * 2 + 2;
			}else {
				counterFee = moneyLong * 0.0005 + 2;
			}
		}else if (TextUtils.equals(mode, mQuickMode)) {
			serviceFee = moneyLong * 0.003;
			String currentHm = DateUtil.getFormatDateTime(date, "HH:mm:ss");
			String s2 = "14:30:00";
			DateFormat df = new SimpleDateFormat("HH:mm:ss");
			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			try
			{
				c1.setTime(df.parse(currentHm));
				c2.setTime(df.parse(s2));
			}catch(java.text.ParseException e){
				e.printStackTrace();
			}
			int result = c1.compareTo(c2);
			if (result > 0) {//在14:30后提现手续费不变
				counterFee = 2.0;
			}else{
				if (dayOfWeek == 6) {//周五
					counterFee = moneyLong * 0.0005 * 3 + 2;
				}else if(dayOfWeek == 7){//周六
					counterFee = moneyLong * 0.0005 * 2 + 2;
				}	else {
					counterFee = moneyLong * 0.0005 + 2;
				}
			}
		}else {
			serviceFee = moneyLong * 0.0025;
			counterFee = 2.0;
		}
		mCounterFeeTv.setText("￥" + StringUtils.getFormatValue(counterFee.toString()));
		mServiceChargeTv.setText("￥" + StringUtils.getFormatValue(serviceFee.toString()));
		if (moneyLong + counterFee + serviceFee < mCanMoney) {//判断提现金额加手续费、服务费是否大于可提现总金额来决定实际到账金额要不要扣除手续费、服务费
			mActualMoney.setText("￥" + StringUtils.getFormatValue(moneyLong.toString()));
		}else
		{
			Double cash = moneyLong - counterFee - serviceFee;
			mActualMoney.setText("￥" + StringUtils.getFormatValue(cash.toString()));
		}
		mMoneyChanged = false;
		if (mDirectSubmit) {
			submit();
		}
	}
	
	boolean mDirectSubmit = false;

	public void submit(){
		if (!isCheck){
			ToastUtils.show(this, "请先勾选同意协议！");
			return;
		}
		if (TextUtils.isEmpty(getStr4TextView(mMoneyTv))) {
			ToastUtils.show(this, "请输入提现金额！");
			return;
		}
		if (mModeOfWithdrawalsRg.getCheckedRadioButtonId() <= 0) {
			ToastUtils.show(this, "请选择提现方式！");
			return;
		}
		String code = getStr4TextView(mCodeEt);
		code = code.toLowerCase();
		if (TextUtils.isEmpty(code)) {
			ToastUtils.show(this, "请输入验证码！");
			return;
		}
		if (TextUtils.isEmpty(mMoneyStr)) {
			ToastUtils.show(this, "申请计算失败，请重新请求！");
			return;
		}
		if (!code.equals(getCode)) {
			ToastUtils.show(this, "验证码错误！");
			return;
		}
		if (mMoneyChanged) {
			mDirectSubmit = true;
			calculateCost(mMoneyStr, mModel);
		}else{
			mDirectSubmit = false;
			Intent intent = new Intent(this,WebViewActivity.class);
			intent.putExtra("title", "提现");
			intent.putExtra("url", getUrl(mMoneyStr,mModel));
			intent.putExtra(Config.GO_BACK, true);
			startActivityForResult(intent, 100);
		}
		
		
	}
	private String getUrl(String money,String cashchl){
		TreeMap<String, String> postValues = new TreeMap<String, String>();
		postValues.put("a", "drawupda");
		postValues.put("money", money);
		postValues.put("m", "User");		
		postValues.put("uid", DeHongApp.mLoginEntity.uid);
		postValues.put("cashchl" , cashchl);
		String device_code = "";
		device_code = JPushInterface.getRegistrationID(this);//传RegistrationID方便后台根据指定RegistrationID推送消息
		DeviceUuidFactory factory = new DeviceUuidFactory(this);
//		device_code = factory.getDeviceUuid() + "";
		LogUtils.e(TAG + ",device_code", "registrationId=" + device_code);
		String phone_type = factory.getPhoneType();
		postValues.put("phone_type", phone_type);
		postValues.put("device_code", device_code);
		postValues.put("platform", "android");
		return WebUrlUtil.getWebUrl(this, Config.getIP() + Config.drawupda, postValues);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == 100) {
			ToastUtils.show(this, "提现成功！");
			setResult(RESULT_OK);
			finishCurrentActivity();
		}
	}

	@Override
	protected int getContentViewId() {
		TAG = getClass().getName();
		return R.layout.act_withdrawals;
	}

	@Override
	public void afterTextChanged(Editable s) {
		mMoneyStr = s.toString();
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mMoneyChanged = true;
	}
	
	OnFocusChangeListener mMoneyTvListener = new OnFocusChangeListener() {
		
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (v == mMoneyTv && !hasFocus) {
				calculateCost(mMoneyStr, mModel);
			}
		}
	};

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		isCheck = isChecked;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.codeIb:
			util = CodeUtil.getInstance();
			mCodeIb.setImageBitmap(util.getBitmap());
			getCode = util.getCode();
			break;
		case R.id.checkBox1:
			Intent intent = new Intent(this,WebViewActivity.class);
			intent.putExtra("title", "德鸿金融会员服务协议");
			intent.putExtra("url", Config.getIP() + Config.hyfwxy);
			intent.putExtra(Config.GO_BACK, true);
			startActivity(intent);
			break;
		case R.id.checkBox2:
			Intent intent2 = new Intent(this,WebViewActivity.class);
			intent2.putExtra("title", "用户隐私协议");
			intent2.putExtra("url", Config.getIP() + Config.yhxsxy);
			startActivity(intent2);
			break;
		case R.id.linearLayout:
			mMoneyTv.clearFocus();
			break;
		case R.id.top_bar_right_txt:
			Intent i = new Intent(this, TransactionActivity.class);
			i.putExtra("page", 2);
			startActivity(i);
			break;
		case R.id.submit_button:
			submit();
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}

}

